{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 49,
   "id": "initial_id",
   "metadata": {
    "collapsed": true,
    "ExecuteTime": {
     "end_time": "2024-03-07T05:18:08.992289Z",
     "start_time": "2024-03-07T05:18:08.973253Z"
    }
   },
   "outputs": [],
   "source": [
    "import pandas as pd\n",
    "import numpy as np\n",
    "import pickle"
   ]
  },
  {
   "cell_type": "code",
   "outputs": [],
   "source": [
    "csitrade=pd.read_csv('ZZ500.csv')\n",
    "# csitrade.rename(columns={'Close':'close'},inplace=True)"
   ],
   "metadata": {
    "collapsed": false,
    "ExecuteTime": {
     "end_time": "2024-03-07T05:18:09.163275Z",
     "start_time": "2024-03-07T05:18:08.994451Z"
    }
   },
   "id": "8601bc5f73d0560b",
   "execution_count": 50
  },
  {
   "cell_type": "code",
   "outputs": [],
   "source": [
    "#数据一定要按股票排序\n",
    "csitrade['close_r']=csitrade['close']/csitrade['close'].shift(1)"
   ],
   "metadata": {
    "collapsed": false,
    "ExecuteTime": {
     "end_time": "2024-03-07T05:18:09.178838Z",
     "start_time": "2024-03-07T05:18:09.164511Z"
    }
   },
   "id": "d245bec416be89af",
   "execution_count": 51
  },
  {
   "cell_type": "code",
   "outputs": [],
   "source": [
    "csitrade.reset_index(inplace=True,drop=True)"
   ],
   "metadata": {
    "collapsed": false,
    "ExecuteTime": {
     "end_time": "2024-03-07T05:18:09.194437Z",
     "start_time": "2024-03-07T05:18:09.180055Z"
    }
   },
   "id": "9009fd15aadd2db5",
   "execution_count": 52
  },
  {
   "cell_type": "code",
   "outputs": [
    {
     "data": {
      "text/plain": "           kdcode          dt  close   open   high    low     turnover  \\\n0       000009.SZ  2018-01-02   7.32   7.27   7.33   7.23  140497530.0   \n1       000009.SZ  2018-01-03   7.42   7.32   7.44   7.30  170636551.0   \n2       000009.SZ  2018-01-04   7.64   7.52   7.70   7.51  358089946.0   \n3       000009.SZ  2018-01-05   7.55   7.65   7.65   7.51  196259451.0   \n4       000009.SZ  2018-01-08   7.52   7.55   7.63   7.46  178511079.0   \n...           ...         ...    ...    ...    ...    ...          ...   \n169007  603883.SH  2023-12-25  29.37  29.02  29.58  28.80  101007153.0   \n169008  603883.SH  2023-12-26  29.05  29.26  29.49  28.82   66158144.0   \n169009  603883.SH  2023-12-27  30.08  28.94  30.40  28.80  206474442.0   \n169010  603883.SH  2023-12-28  28.98  30.15  30.20  28.44  264520627.0   \n169011  603883.SH  2023-12-29  29.89  28.97  30.00  28.80  204020452.0   \n\n            volume   close_r  \n0       19269993.0       NaN  \n1       23092097.0  1.013661  \n2       46992707.0  1.029650  \n3       25990264.0  0.988220  \n4       23703431.0  0.996026  \n...            ...       ...  \n169007   3457490.0  1.012061  \n169008   2272587.0  0.989105  \n169009   6939076.0  1.035456  \n169010   9053474.0  0.963431  \n169011   6878338.0  1.031401  \n\n[169012 rows x 9 columns]",
      "text/html": "<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>kdcode</th>\n      <th>dt</th>\n      <th>close</th>\n      <th>open</th>\n      <th>high</th>\n      <th>low</th>\n      <th>turnover</th>\n      <th>volume</th>\n      <th>close_r</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>0</th>\n      <td>000009.SZ</td>\n      <td>2018-01-02</td>\n      <td>7.32</td>\n      <td>7.27</td>\n      <td>7.33</td>\n      <td>7.23</td>\n      <td>140497530.0</td>\n      <td>19269993.0</td>\n      <td>NaN</td>\n    </tr>\n    <tr>\n      <th>1</th>\n      <td>000009.SZ</td>\n      <td>2018-01-03</td>\n      <td>7.42</td>\n      <td>7.32</td>\n      <td>7.44</td>\n      <td>7.30</td>\n      <td>170636551.0</td>\n      <td>23092097.0</td>\n      <td>1.013661</td>\n    </tr>\n    <tr>\n      <th>2</th>\n      <td>000009.SZ</td>\n      <td>2018-01-04</td>\n      <td>7.64</td>\n      <td>7.52</td>\n      <td>7.70</td>\n      <td>7.51</td>\n      <td>358089946.0</td>\n      <td>46992707.0</td>\n      <td>1.029650</td>\n    </tr>\n    <tr>\n      <th>3</th>\n      <td>000009.SZ</td>\n      <td>2018-01-05</td>\n      <td>7.55</td>\n      <td>7.65</td>\n      <td>7.65</td>\n      <td>7.51</td>\n      <td>196259451.0</td>\n      <td>25990264.0</td>\n      <td>0.988220</td>\n    </tr>\n    <tr>\n      <th>4</th>\n      <td>000009.SZ</td>\n      <td>2018-01-08</td>\n      <td>7.52</td>\n      <td>7.55</td>\n      <td>7.63</td>\n      <td>7.46</td>\n      <td>178511079.0</td>\n      <td>23703431.0</td>\n      <td>0.996026</td>\n    </tr>\n    <tr>\n      <th>...</th>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n    </tr>\n    <tr>\n      <th>169007</th>\n      <td>603883.SH</td>\n      <td>2023-12-25</td>\n      <td>29.37</td>\n      <td>29.02</td>\n      <td>29.58</td>\n      <td>28.80</td>\n      <td>101007153.0</td>\n      <td>3457490.0</td>\n      <td>1.012061</td>\n    </tr>\n    <tr>\n      <th>169008</th>\n      <td>603883.SH</td>\n      <td>2023-12-26</td>\n      <td>29.05</td>\n      <td>29.26</td>\n      <td>29.49</td>\n      <td>28.82</td>\n      <td>66158144.0</td>\n      <td>2272587.0</td>\n      <td>0.989105</td>\n    </tr>\n    <tr>\n      <th>169009</th>\n      <td>603883.SH</td>\n      <td>2023-12-27</td>\n      <td>30.08</td>\n      <td>28.94</td>\n      <td>30.40</td>\n      <td>28.80</td>\n      <td>206474442.0</td>\n      <td>6939076.0</td>\n      <td>1.035456</td>\n    </tr>\n    <tr>\n      <th>169010</th>\n      <td>603883.SH</td>\n      <td>2023-12-28</td>\n      <td>28.98</td>\n      <td>30.15</td>\n      <td>30.20</td>\n      <td>28.44</td>\n      <td>264520627.0</td>\n      <td>9053474.0</td>\n      <td>0.963431</td>\n    </tr>\n    <tr>\n      <th>169011</th>\n      <td>603883.SH</td>\n      <td>2023-12-29</td>\n      <td>29.89</td>\n      <td>28.97</td>\n      <td>30.00</td>\n      <td>28.80</td>\n      <td>204020452.0</td>\n      <td>6878338.0</td>\n      <td>1.031401</td>\n    </tr>\n  </tbody>\n</table>\n<p>169012 rows × 9 columns</p>\n</div>"
     },
     "execution_count": 53,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "csitrade"
   ],
   "metadata": {
    "collapsed": false,
    "ExecuteTime": {
     "end_time": "2024-03-07T05:18:09.225168Z",
     "start_time": "2024-03-07T05:18:09.196698Z"
    }
   },
   "id": "364594070f3a447b",
   "execution_count": 53
  },
  {
   "cell_type": "code",
   "outputs": [],
   "source": [
    "#大盘和日收益率\n",
    "import pandas as pd\n",
    "df_trade=csitrade\n",
    "df_trade.rename(columns={'kdcode':'instrument','dt':'datetime'},inplace=True)\n",
    "# df_trade.rename(columns={'company':'instrument','Date':'datetime'},inplace=True)\n",
    "df_trade['datetime'] = df_trade['datetime'].astype('datetime64[ns]')"
   ],
   "metadata": {
    "collapsed": false,
    "ExecuteTime": {
     "end_time": "2024-03-07T05:18:09.318179Z",
     "start_time": "2024-03-07T05:18:09.226285Z"
    }
   },
   "id": "697287ae73471b39",
   "execution_count": 54
  },
  {
   "cell_type": "code",
   "outputs": [],
   "source": [
    "df_trade=df_trade[df_trade['datetime']>'2022-12-31']"
   ],
   "metadata": {
    "collapsed": false,
    "ExecuteTime": {
     "end_time": "2024-03-07T05:18:09.348996Z",
     "start_time": "2024-03-07T05:18:09.319331Z"
    }
   },
   "id": "5b0f857300a4c7cd",
   "execution_count": 55
  },
  {
   "cell_type": "code",
   "outputs": [],
   "source": [
    "df_trade.reset_index(inplace=True,drop=True)"
   ],
   "metadata": {
    "collapsed": false,
    "ExecuteTime": {
     "end_time": "2024-03-07T05:18:09.364054Z",
     "start_time": "2024-03-07T05:18:09.350242Z"
    }
   },
   "id": "587f79b101ede03f",
   "execution_count": 56
  },
  {
   "cell_type": "code",
   "outputs": [
    {
     "data": {
      "text/plain": "      instrument   datetime  close   open   high    low     turnover  \\\n0      000009.SZ 2023-01-03  12.22  12.06  12.25  11.91  226093346.0   \n1      000009.SZ 2023-01-04  12.15  12.16  12.30  12.08  223670172.0   \n2      000009.SZ 2023-01-05  12.26  12.18  12.35  12.12  308517291.0   \n3      000009.SZ 2023-01-06  12.28  12.26  12.42  12.19  332819569.0   \n4      000009.SZ 2023-01-09  12.19  12.39  12.39  12.15  272123102.0   \n...          ...        ...    ...    ...    ...    ...          ...   \n28067  603883.SH 2023-12-25  29.37  29.02  29.58  28.80  101007153.0   \n28068  603883.SH 2023-12-26  29.05  29.26  29.49  28.82   66158144.0   \n28069  603883.SH 2023-12-27  30.08  28.94  30.40  28.80  206474442.0   \n28070  603883.SH 2023-12-28  28.98  30.15  30.20  28.44  264520627.0   \n28071  603883.SH 2023-12-29  29.89  28.97  30.00  28.80  204020452.0   \n\n           volume   close_r  \n0      18635349.0  1.010753  \n1      18369170.0  0.994272  \n2      25151630.0  1.009053  \n3      27004871.0  1.001631  \n4      22219856.0  0.992671  \n...           ...       ...  \n28067   3457490.0  1.012061  \n28068   2272587.0  0.989105  \n28069   6939076.0  1.035456  \n28070   9053474.0  0.963431  \n28071   6878338.0  1.031401  \n\n[28072 rows x 9 columns]",
      "text/html": "<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>instrument</th>\n      <th>datetime</th>\n      <th>close</th>\n      <th>open</th>\n      <th>high</th>\n      <th>low</th>\n      <th>turnover</th>\n      <th>volume</th>\n      <th>close_r</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>0</th>\n      <td>000009.SZ</td>\n      <td>2023-01-03</td>\n      <td>12.22</td>\n      <td>12.06</td>\n      <td>12.25</td>\n      <td>11.91</td>\n      <td>226093346.0</td>\n      <td>18635349.0</td>\n      <td>1.010753</td>\n    </tr>\n    <tr>\n      <th>1</th>\n      <td>000009.SZ</td>\n      <td>2023-01-04</td>\n      <td>12.15</td>\n      <td>12.16</td>\n      <td>12.30</td>\n      <td>12.08</td>\n      <td>223670172.0</td>\n      <td>18369170.0</td>\n      <td>0.994272</td>\n    </tr>\n    <tr>\n      <th>2</th>\n      <td>000009.SZ</td>\n      <td>2023-01-05</td>\n      <td>12.26</td>\n      <td>12.18</td>\n      <td>12.35</td>\n      <td>12.12</td>\n      <td>308517291.0</td>\n      <td>25151630.0</td>\n      <td>1.009053</td>\n    </tr>\n    <tr>\n      <th>3</th>\n      <td>000009.SZ</td>\n      <td>2023-01-06</td>\n      <td>12.28</td>\n      <td>12.26</td>\n      <td>12.42</td>\n      <td>12.19</td>\n      <td>332819569.0</td>\n      <td>27004871.0</td>\n      <td>1.001631</td>\n    </tr>\n    <tr>\n      <th>4</th>\n      <td>000009.SZ</td>\n      <td>2023-01-09</td>\n      <td>12.19</td>\n      <td>12.39</td>\n      <td>12.39</td>\n      <td>12.15</td>\n      <td>272123102.0</td>\n      <td>22219856.0</td>\n      <td>0.992671</td>\n    </tr>\n    <tr>\n      <th>...</th>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n    </tr>\n    <tr>\n      <th>28067</th>\n      <td>603883.SH</td>\n      <td>2023-12-25</td>\n      <td>29.37</td>\n      <td>29.02</td>\n      <td>29.58</td>\n      <td>28.80</td>\n      <td>101007153.0</td>\n      <td>3457490.0</td>\n      <td>1.012061</td>\n    </tr>\n    <tr>\n      <th>28068</th>\n      <td>603883.SH</td>\n      <td>2023-12-26</td>\n      <td>29.05</td>\n      <td>29.26</td>\n      <td>29.49</td>\n      <td>28.82</td>\n      <td>66158144.0</td>\n      <td>2272587.0</td>\n      <td>0.989105</td>\n    </tr>\n    <tr>\n      <th>28069</th>\n      <td>603883.SH</td>\n      <td>2023-12-27</td>\n      <td>30.08</td>\n      <td>28.94</td>\n      <td>30.40</td>\n      <td>28.80</td>\n      <td>206474442.0</td>\n      <td>6939076.0</td>\n      <td>1.035456</td>\n    </tr>\n    <tr>\n      <th>28070</th>\n      <td>603883.SH</td>\n      <td>2023-12-28</td>\n      <td>28.98</td>\n      <td>30.15</td>\n      <td>30.20</td>\n      <td>28.44</td>\n      <td>264520627.0</td>\n      <td>9053474.0</td>\n      <td>0.963431</td>\n    </tr>\n    <tr>\n      <th>28071</th>\n      <td>603883.SH</td>\n      <td>2023-12-29</td>\n      <td>29.89</td>\n      <td>28.97</td>\n      <td>30.00</td>\n      <td>28.80</td>\n      <td>204020452.0</td>\n      <td>6878338.0</td>\n      <td>1.031401</td>\n    </tr>\n  </tbody>\n</table>\n<p>28072 rows × 9 columns</p>\n</div>"
     },
     "execution_count": 57,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "df_trade"
   ],
   "metadata": {
    "collapsed": false,
    "ExecuteTime": {
     "end_time": "2024-03-07T05:18:09.395898Z",
     "start_time": "2024-03-07T05:18:09.365185Z"
    }
   },
   "id": "fc9b7a968042dffe",
   "execution_count": 57
  },
  {
   "cell_type": "code",
   "outputs": [],
   "source": [
    "index_date_unique = df_trade['datetime'].unique().tolist()"
   ],
   "metadata": {
    "collapsed": false,
    "ExecuteTime": {
     "end_time": "2024-03-07T05:18:09.411870Z",
     "start_time": "2024-03-07T05:18:09.397331Z"
    }
   },
   "id": "e36abc36289710dd",
   "execution_count": 58
  },
  {
   "cell_type": "code",
   "outputs": [],
   "source": [
    "#qlib交易策略\n",
    "path='TRA/output/zz500/transformer_tra/pred.pkl'\n",
    "f=open(path,'rb')\n",
    "data=pickle.load(f)\n",
    "df=pd.DataFrame(data)\n",
    "#df.reset_index(inplace=True)\n",
    "#df=df[df['datetime']<'2021-12-30']\n",
    "df.reset_index(inplace=True)\n",
    "df.rename(columns={'kdcode':'instrument','dt':'datetime'},inplace=True)\n",
    "# df.rename(columns={'Company':'instrument','Date':'datetime'},inplace=True)\n",
    "df_score=pd.DataFrame()\n",
    "#for date in index_date_unique[:-1]:\n",
    "for date in index_date_unique:\n",
    "   # loc=np.where(index_date_unique==date)\n",
    "    #nextdate_loc=np.where(index_date_unique==date)[0][0]+1\n",
    "    for i in range(0,len(df)):\n",
    "        if df['datetime'][i]== date:\n",
    "            b={'datetime':date,'instrument':df['instrument'][i],'score':df['score'][i]}\n",
    "            df_score=df_score._append(b,ignore_index=True)\n",
    "x=pd.merge(df_trade,df_score,on=['datetime','instrument'],how='outer')\n",
    "trade_date_unique=df_trade['datetime'].unique()\n",
    "df_return=pd.DataFrame()\n",
    "#b={'datetime':trade_date_unique[0],'daily_return':0}\n",
    "#df_return=df_return.append(b,ignore_index=True)\n",
    "for date in trade_date_unique:\n",
    "    x_day=x[x['datetime']==date]\n",
    "    r_day=x_day.nlargest(9,columns='score').close_r.mean()\n",
    "    r_day=r_day-1\n",
    "    #r_day-=x_day.nsmallest(9,columns='score').close_r.mean()\n",
    "    b={'datetime':date,'daily_return':r_day}\n",
    "    df_return=df_return._append(b,ignore_index=True)"
   ],
   "metadata": {
    "collapsed": false,
    "ExecuteTime": {
     "end_time": "2024-03-07T05:19:41.940196Z",
     "start_time": "2024-03-07T05:18:09.413042Z"
    }
   },
   "id": "6e31a0957e1f2f73",
   "execution_count": 59
  },
  {
   "cell_type": "code",
   "outputs": [],
   "source": [
    "portfolio_df_performance = df_return.set_index(['datetime'])"
   ],
   "metadata": {
    "collapsed": false,
    "ExecuteTime": {
     "end_time": "2024-03-07T05:19:41.955755Z",
     "start_time": "2024-03-07T05:19:41.941197Z"
    }
   },
   "id": "e810e231c46eabe3",
   "execution_count": 60
  },
  {
   "cell_type": "code",
   "outputs": [
    {
     "data": {
      "text/plain": "            daily_return\ndatetime                \n2023-01-03      1.024722\n2023-01-04      1.026788\n2023-01-05      1.041130\n2023-01-06      1.040629\n2023-01-09      1.054733\n...                  ...\n2023-12-25      1.101277\n2023-12-26      1.097398\n2023-12-27      1.105964\n2023-12-28      1.110145\n2023-12-29      1.120308\n\n[242 rows x 1 columns]",
      "text/html": "<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>daily_return</th>\n    </tr>\n    <tr>\n      <th>datetime</th>\n      <th></th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>2023-01-03</th>\n      <td>1.024722</td>\n    </tr>\n    <tr>\n      <th>2023-01-04</th>\n      <td>1.026788</td>\n    </tr>\n    <tr>\n      <th>2023-01-05</th>\n      <td>1.041130</td>\n    </tr>\n    <tr>\n      <th>2023-01-06</th>\n      <td>1.040629</td>\n    </tr>\n    <tr>\n      <th>2023-01-09</th>\n      <td>1.054733</td>\n    </tr>\n    <tr>\n      <th>...</th>\n      <td>...</td>\n    </tr>\n    <tr>\n      <th>2023-12-25</th>\n      <td>1.101277</td>\n    </tr>\n    <tr>\n      <th>2023-12-26</th>\n      <td>1.097398</td>\n    </tr>\n    <tr>\n      <th>2023-12-27</th>\n      <td>1.105964</td>\n    </tr>\n    <tr>\n      <th>2023-12-28</th>\n      <td>1.110145</td>\n    </tr>\n    <tr>\n      <th>2023-12-29</th>\n      <td>1.120308</td>\n    </tr>\n  </tbody>\n</table>\n<p>242 rows × 1 columns</p>\n</div>"
     },
     "execution_count": 61,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "ARR = (1 + portfolio_df_performance).cumprod()\n",
    "ARR"
   ],
   "metadata": {
    "collapsed": false,
    "ExecuteTime": {
     "end_time": "2024-03-07T05:19:41.971425Z",
     "start_time": "2024-03-07T05:19:41.958268Z"
    }
   },
   "id": "abfd8d3aaa8ea721",
   "execution_count": 61
  },
  {
   "cell_type": "code",
   "outputs": [
    {
     "data": {
      "text/plain": "            daily_return\ndatetime                \n2023-01-03      0.024722\n2023-01-04      0.002016\n2023-01-05      0.013967\n2023-01-06     -0.000481\n2023-01-09      0.013553\n...                  ...\n2023-12-25     -0.008798\n2023-12-26     -0.003522\n2023-12-27      0.007806\n2023-12-28      0.003781\n2023-12-29      0.009154\n\n[242 rows x 1 columns]",
      "text/html": "<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>daily_return</th>\n    </tr>\n    <tr>\n      <th>datetime</th>\n      <th></th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>2023-01-03</th>\n      <td>0.024722</td>\n    </tr>\n    <tr>\n      <th>2023-01-04</th>\n      <td>0.002016</td>\n    </tr>\n    <tr>\n      <th>2023-01-05</th>\n      <td>0.013967</td>\n    </tr>\n    <tr>\n      <th>2023-01-06</th>\n      <td>-0.000481</td>\n    </tr>\n    <tr>\n      <th>2023-01-09</th>\n      <td>0.013553</td>\n    </tr>\n    <tr>\n      <th>...</th>\n      <td>...</td>\n    </tr>\n    <tr>\n      <th>2023-12-25</th>\n      <td>-0.008798</td>\n    </tr>\n    <tr>\n      <th>2023-12-26</th>\n      <td>-0.003522</td>\n    </tr>\n    <tr>\n      <th>2023-12-27</th>\n      <td>0.007806</td>\n    </tr>\n    <tr>\n      <th>2023-12-28</th>\n      <td>0.003781</td>\n    </tr>\n    <tr>\n      <th>2023-12-29</th>\n      <td>0.009154</td>\n    </tr>\n  </tbody>\n</table>\n<p>242 rows × 1 columns</p>\n</div>"
     },
     "execution_count": 62,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "portfolio_df_performance"
   ],
   "metadata": {
    "collapsed": false,
    "ExecuteTime": {
     "end_time": "2024-03-07T05:19:42.002421Z",
     "start_time": "2024-03-07T05:19:41.976426Z"
    }
   },
   "id": "1888f991efa2c131",
   "execution_count": 62
  },
  {
   "cell_type": "code",
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "C:\\Users\\胡逸凡\\AppData\\Local\\Temp\\ipykernel_13976\\980728215.py:12: FutureWarning: 'm' is deprecated and will be removed in a future version, please use 'ME' instead.\n",
      "  monthly_statistics_df = alpha_df_performance[net_value_columns].resample('m').last()\n",
      "C:\\Users\\胡逸凡\\AppData\\Local\\Temp\\ipykernel_13976\\980728215.py:20: FutureWarning: 'y' is deprecated and will be removed in a future version, please use 'YE' instead.\n",
      "  yearly_statistics_df = alpha_df_performance[net_value_columns].resample('y').last()\n",
      "C:\\Users\\胡逸凡\\AppData\\Roaming\\Python\\Python310\\site-packages\\numpy\\core\\fromnumeric.py:3643: FutureWarning: The behavior of DataFrame.std with axis=None is deprecated, in a future version this will reduce over both axes and return a scalar. To retain the old behavior, pass axis=0 (or do not pass axis)\n",
      "  return std(axis=axis, dtype=dtype, out=out, ddof=ddof, **kwargs)\n",
      "C:\\Users\\胡逸凡\\AppData\\Roaming\\Python\\Python310\\site-packages\\numpy\\core\\fromnumeric.py:3643: FutureWarning: The behavior of DataFrame.std with axis=None is deprecated, in a future version this will reduce over both axes and return a scalar. To retain the old behavior, pass axis=0 (or do not pass axis)\n",
      "  return std(axis=axis, dtype=dtype, out=out, ddof=ddof, **kwargs)\n",
      "C:\\Users\\胡逸凡\\AppData\\Roaming\\Python\\Python310\\site-packages\\numpy\\core\\fromnumeric.py:3643: FutureWarning: The behavior of DataFrame.std with axis=None is deprecated, in a future version this will reduce over both axes and return a scalar. To retain the old behavior, pass axis=0 (or do not pass axis)\n",
      "  return std(axis=axis, dtype=dtype, out=out, ddof=ddof, **kwargs)\n"
     ]
    }
   ],
   "source": [
    "alpha_df_performance = pd.DataFrame()\n",
    "alpha_df_performance['portfolio_daily_return'] = portfolio_df_performance['daily_return']\n",
    "alpha_df_performance['portfolio_net_value'] = (alpha_df_performance['portfolio_daily_return'] + 1).cumprod()\n",
    "\n",
    "net_value_columns = ['portfolio_net_value']\n",
    "\n",
    "alpha_statistics_df = pd.DataFrame(index=alpha_df_performance[net_value_columns].columns,\n",
    "                                    columns=[\"年化收益\", \"年化波动率\", \"最大回撤率\", \"夏普率\", \"Calmar\", \"IR\"])\n",
    "\n",
    "# alpha_df_performance.set_index(\"dt\", inplace=True)\n",
    "alpha_df_performance.index = pd.to_datetime(alpha_df_performance.index)\n",
    "monthly_statistics_df = alpha_df_performance[net_value_columns].resample('m').last()\n",
    "monthly_statistics_df = pd.concat([alpha_df_performance[:1][\n",
    "                                        ['portfolio_net_value']],\n",
    "                                    monthly_statistics_df])\n",
    "monthly_statistics_df = monthly_statistics_df.pct_change()\n",
    "monthly_statistics_df = monthly_statistics_df.dropna()\n",
    "monthly_statistics_df.index = monthly_statistics_df.index.date\n",
    "## TODO 补充第一年的数据\n",
    "yearly_statistics_df = alpha_df_performance[net_value_columns].resample('y').last()\n",
    "yearly_statistics_df = pd.concat([alpha_df_performance[:1][\n",
    "                                        ['portfolio_net_value']],\n",
    "                                    yearly_statistics_df])\n",
    "yearly_statistics_df = yearly_statistics_df.pct_change()\n",
    "yearly_statistics_df = yearly_statistics_df.dropna()\n",
    "yearly_statistics_df.index = yearly_statistics_df.index.date\n",
    "\n",
    "alpha_statistics_df.loc[:, \"年化收益\"] = np.mean(\n",
    "    (alpha_df_performance[net_value_columns].tail(1)) ** (252 / len(alpha_df_performance)) - 1)\n",
    "alpha_statistics_df.loc[:, \"年化波动率\"] = np.std(\n",
    "    alpha_df_performance[net_value_columns] / alpha_df_performance[net_value_columns].shift(1) - 1) * np.sqrt(\n",
    "    252)\n",
    "alpha_statistics_df.loc[:, \"累积收益\"] = np.mean(alpha_df_performance[net_value_columns].tail(1) - 1)\n",
    "alpha_statistics_df.loc[:, \"累积波动率\"] = np.std(\n",
    "    alpha_df_performance[net_value_columns] / alpha_df_performance[net_value_columns].shift(1) - 1)\n",
    "alpha_statistics_df.loc[:, \"最大回撤率\"] = np.min(\n",
    "    (alpha_df_performance[net_value_columns] - alpha_df_performance[net_value_columns].cummax()) /\n",
    "    alpha_df_performance[net_value_columns].cummax())\n",
    "alpha_statistics_df.loc[:, \"夏普率\"] = alpha_statistics_df[\"年化收益\"] / alpha_statistics_df[\"年化波动率\"]\n",
    "alpha_statistics_df.loc[:, \"Calmar\"] = alpha_statistics_df[\"年化收益\"] / abs(alpha_statistics_df[\"最大回撤率\"])\n",
    "alpha_statistics_df.loc[:, \"IR\"] = np.mean(\n",
    "    alpha_df_performance[net_value_columns] / alpha_df_performance[net_value_columns].shift(1) - 1) * np.sqrt(\n",
    "    252) / np.std(alpha_df_performance[net_value_columns] / alpha_df_performance[net_value_columns].shift(1) - 1)"
   ],
   "metadata": {
    "collapsed": false,
    "ExecuteTime": {
     "end_time": "2024-03-07T05:19:42.065692Z",
     "start_time": "2024-03-07T05:19:42.006422Z"
    }
   },
   "id": "8d9c7617b9d87b48",
   "execution_count": 63
  },
  {
   "cell_type": "code",
   "outputs": [
    {
     "data": {
      "text/plain": "                        年化收益     年化波动率     最大回撤率       夏普率    Calmar  \\\nportfolio_net_value  0.12558  0.161882 -0.144962  0.775749  0.866293   \n\n                           IR      累积收益     累积波动率  \nportfolio_net_value  0.656948  0.120308  0.010198  ",
      "text/html": "<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>年化收益</th>\n      <th>年化波动率</th>\n      <th>最大回撤率</th>\n      <th>夏普率</th>\n      <th>Calmar</th>\n      <th>IR</th>\n      <th>累积收益</th>\n      <th>累积波动率</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>portfolio_net_value</th>\n      <td>0.12558</td>\n      <td>0.161882</td>\n      <td>-0.144962</td>\n      <td>0.775749</td>\n      <td>0.866293</td>\n      <td>0.656948</td>\n      <td>0.120308</td>\n      <td>0.010198</td>\n    </tr>\n  </tbody>\n</table>\n</div>"
     },
     "execution_count": 64,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "alpha_statistics_df"
   ],
   "metadata": {
    "collapsed": false,
    "ExecuteTime": {
     "end_time": "2024-03-07T05:19:42.082616Z",
     "start_time": "2024-03-07T05:19:42.068015Z"
    }
   },
   "id": "387f266a48f67921",
   "execution_count": 64
  },
  {
   "cell_type": "markdown",
   "source": [
    "ASR = ARR / AVol;   CR = ARR / abs(MDD)\n",
    "                        ARR    AVol    MDD    ASR     CR    IR\n",
    "hs300  lstm            -0.214  0.157  -0.275 -1.361 -0.779 -1.492\n",
    "       lstm tra        -0.216  0.164  -0.294 -1.314 -0.735 -1.461\n",
    "       gru             -0.229  0.156  -0.290 -1.469 -0.790 -1.631\n",
    "       transformer     -0.240  0.156  -0.281 -1.543 -0.855 -1.695\n",
    "       transformer tra -0.074  0.169  -0.222 -0.436 -0.332 -0.409\n",
    "      \n",
    "zz500  lstm            -0.008  0.159  -0.172 -0.047 -0.044 -0.128\n",
    "       lstm tra         0.016  0.162  -0.192  0.101  0.086  0.014\n",
    "       gru             -0.004  0.159  -0.193 -0.028 -0.023 -0.118\n",
    "       transformer      0.154  0.156  -0.135  0.986  1.143  0.867\n",
    "       transformer tra  0.125  0.162  -0.145  0.776  0.866  0.657\n",
    "      \n",
    "sp500  lstm            0.142  0.162  -0.178  0.877  0.798  0.929\n",
    "       lstm tra        0.191  0.161  -0.150  1.186  1.273  1.115\n",
    "       gru             0.324  0.169  -0.139  1.917  2.331  1.657\n",
    "       transformer     0.135  0.159  -0.140  0.852  0.968  0.908\n",
    "       transformer tra 0.184  0.166  -0.158  1.114  1.172  1.106\n",
    "      \n",
    "nas100 lstm            0.247  0.176  -0.128  1.403  1.930  1.386\n",
    "       lstm tra        0.201  0.192  -0.183  1.047  1.098  1.032\n",
    "       gru             0.225  0.188  -0.165  1.197  1.364  1.160\n",
    "       transformer     0.268  0.175  -0.131  1.531  2.046  1.441\n",
    "       transformer tra 0.267  0.181  -0.144  1.475  1.854  1.427\n",
    "       "
   ],
   "metadata": {
    "collapsed": false
   },
   "id": "b2140841825435a"
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 2
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython2",
   "version": "2.7.6"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
